<template>
  <div class="div_sty">
    <div class="container">
      <el-row>
        <el-col :span="15" style="font-size: 22px;margin-top: 6px;">用户管理</el-col>
        <el-col :span="2"><el-button type="primary" @click="addEmp" v-if="perssionButton.indexOf('emp_edit') >-1">添加用户</el-button></el-col>
        <el-col :span="7"> <span style="color: #D6CCCF"> &nbsp;&nbsp;  | &nbsp;&nbsp;</span>
          <span style="color: #667B8F">搜索：</span><el-input v-model="empName"  @change="searchEmp" style="margin-left: 10px;width:206px;" suffix-icon="el-icon-search" placeholder="请输入用户姓名"></el-input></el-col>
      </el-row>
      <el-divider></el-divider>
          <el-tabs :tab-position="tabPosition" style="height:100%" @tab-click="handleClick">
            <el-tab-pane v-for="(dept,index) in userInfo" :label="`${dept.deptName}(${dept.empList.length})`" :key="dept.deptsId">
              <el-row :gutter="20" style="margin-left: 1%;">
                        <el-col :span="8" v-for="(emp,index) in dept.empList.slice((pageNum-1)*pageSize,pageNum*pageSize)"  :key="emp.employeesId">
                          <el-card shadow="hover" class="mgb20" style="height:252px;width:305px;">
                            <div class="user-info" @click="userdetails(dept,emp)">
                              <img  :src="emp.empImgpath" style="border-radius: 50%;width:60px;height:60px;" />
                              <div class="user-info-cont">
                                <div class="user-info-name">{{emp.empName}}</div>
                                <div>{{emp.empPhone}}</div>
                              </div>
                            </div>
                            <div class="user-info-list">
                              <el-row>
                                <el-col :span="8">
                                  用户状态:
                                </el-col>
                        <el-col :span="16" >
                          <el-switch style="display: block" :disabled="id==emp.employeesId"  v-model="emp.empIsNot"  active-color="#13ce66" @change="updateEmpStatus(emp)"
                            inactive-color="#ff4949" active-value=1  inactive-value=0 active-text="启用"  inactive-text="禁用">
                          </el-switch>
                        </el-col>
                      </el-row>
                      <el-row>
                        <el-col :span="8">
                          用户职位:
                        </el-col>
                        <el-col :span="16" >
                          <el-tag size="mini" v-for="(role,index) in emp.positionVos" :key="index" style="margin-left:2px;">{{role.label}}</el-tag>
                        </el-col>
                      </el-row>
                      <el-row>
                        <el-col :span="8">
                          入职日期:
                        </el-col>
                        <el-col :span="16" >
                         {{emp.dateEntry}}
                        </el-col>
                      </el-row>

                      <el-row>
                        <el-col :span="8">
                          操作:
                        </el-col>
                        <el-col :span="16" >
                          <el-button type="primary" style="padding: 3px 5px" @click="updateEmp(dept,emp)"  v-if="perssionButton.indexOf('emp_edit') >-1">修改</el-button>
                       <!--   <el-button type="primary" style="padding: 3px 5px" @click="deleteEmp(emp) " v-if="perssionButton.indexOf('emp_delete') >-1" >删除</el-button>-->
                          <el-button type="primary" style="padding: 3px 5px" @click="restPwd(emp)">重置</el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="float: right"
                :page-sizes="[3, 6, 9, 12]"
                :page-size="pageSize"
                :current-page="pageNum"
                layout="total, sizes, prev, pager, next, jumper"
                :total="dept.empList.length">
              </el-pagination>
            </el-tab-pane>
          </el-tabs>

    <!--个人详细信息-->
    <el-dialog title="详细信息"  :visible.sync="userVisable" >
        <el-form label-width="80px" :model="employeeDetails">
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户名称:"  class="userInfomantion">
                <el-input style="width:200px;" v-model="employeeDetails.empName" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话:"  class="userInfomantion">
                <el-input style="width:200px;" v-model="employeeDetails.empPhone" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别:"  class="userInfomantion">
                <el-input style="width:200px;" v-model="employeeDetails.empSex" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号:"  class="userInfomantion">
                <el-input style="width:200px;" value="430224200009160660" v-model="employeeDetails.empCard" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户状态:"  class="userInfomantion">
                <el-input style="width:200px;" v-model="employeeDetails.empIsNot" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门:"  class="userInfomantion">
                <el-input style="width:200px;"v-model="employeeDetails.deptName" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色:"  class="userInfomantion">
                <el-input style="width:200px;"  v-if="employeeDetails.positionList.length ==1 " v-for=" (emp,index) in employeeDetails.positionList" :key="index" :value="emp.label" readonly></el-input>
                <el-input  v-if="employeeDetails.positionList.length >1" style="width:100px;" v-for=" (emp,index) in employeeDetails.positionList" :key="index" :value="emp.label" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职日期:"  class="userInfomantion">
                <el-input style="width:200px;" v-model="employeeDetails.dateEntry" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="地址:"  class="userInfomantion">
                <el-input style="width:520px;" v-model="employeeDetails.empAddress" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="userVisable = false">返回</el-button>
          </span>
    </el-dialog>

    <el-dialog :title="title"  :visible.sync="addUser" width="38%" >
      <el-form  :model="employee" style="margin-left: 44px;height:420px;" :rules="employeeRules" ref="employeeForm" :label-position="labelPosition" label-width="90px">
     <el-scrollbar style="height: 100%">
       <el-form-item label="用户名称:"  prop="empName">
         <el-input v-model="employee.empName" style="width:250px;" ></el-input>
       </el-form-item>
       <el-form-item label="联系电话:"  prop="empPhone">
         <el-input v-model="employee.empPhone" style="width:250px;"></el-input>
       </el-form-item>
       <el-form-item label="身份证号:" prop="empCard">
         <el-input v-model="employee.empCard" style="width:250px;"></el-input>
       </el-form-item>
       <el-form-item label="性别:" prop="empSex">
         <el-radio-group v-model="employee.empSex">
           <el-radio  label="男"></el-radio>
           <el-radio  label="女"></el-radio>
         </el-radio-group>
       </el-form-item>
       <el-form-item label="状态:">
         <el-switch  v-model="employee.empIsNot" style="display: block;margin-top: 8px;"  active-color="#13ce66"
           inactive-color="#ff4949" active-value='1' inactive-value='0' active-text="启用"  inactive-text="禁用" >
         </el-switch>
       </el-form-item>
       <el-form-item label="地址:" prop="empAddressArea">
         <v-distpicker  :province="employee.empAddressProvince" @province="ChangeProvince"
                        :city="employee.empAddressCity" @city="ChangeCity"
                        :area="employee.empAddressArea" @area="ChangeArea"
                         class="distpicker-address-wrapper"></v-distpicker>
       </el-form-item>
       <el-form-item label="详细地址:" prop="empAddressDetailed">
         <el-input  v-model="employee.empAddressDetailed" style="width:250px;"></el-input>
       </el-form-item>
       <el-form-item label="部门:" prop="deptByDeptsId.deptName">
         <el-select v-model="employee.deptByDeptsId" filterable  value-key="deptsId" style="width:250px" @change="findPosition(employee.deptByDeptsId.deptsId)" placeholder="请选择">
           <el-option v-for=" dept in deptList" :key="dept.deptsId" :label="dept.deptName" :value="dept"></el-option>
         </el-select>
       </el-form-item>

       <el-form-item label="职位:" prop="positionList">
         <el-select  v-model="employee.positionList[0]"  style="width:250px" placeholder="请选择">
           <el-option v-for="position in positionList" :disabled="postOne==position.postId" :key="position.postId" :label="position.postName" :value="position.postId" ></el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="入职日期:" prop="dateEntry">
         <el-date-picker type="date"  readonly v-model="employee.dateEntry" placeholder="选择日期" format="yyyy-MM-dd" style="width:250px">
         </el-date-picker>
       </el-form-item>
     </el-scrollbar>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUser = false">取 消</el-button>
        <el-button type="primary" @click="saveEmp">确 定</el-button>
      </span>
    </el-dialog>
    </div>
  </div>
</template>

<script>
  import VDistpicker from 'v-distpicker'
  export default {
    name: 'Sareturnorder',
    components: { VDistpicker },
    data() {
      var checkedEmpName = (rule, value, callback) => {
        if(this.updateEmpname == value){
          callback();
        }else{
          this.$axios.get("http://localhost:8088/emp/is_no_emp",
            {params:{empName:value}}).then(v=>{
            if(v.data == 1){
              callback(new Error('用户名已存在，请重新输入'));
            }else{
              callback();
            }
          }).catch();
        }

      };

      var checkedPost = (rule, value, callback) => {
       if(value.length=0){
         callback(new Error('职位不能为空'));
       }else{
         callback();
        }
      };

      var checkedPhone = (rule, value, callback) => {
        if(this.updateEmpphone==value){
          callback();
        }else{
          this.$axios.get("http://localhost:8088/emp/emp_phone",
            {params:{
                phone:value
              }}).then(v=>{
            if(v.data == 1){
              callback(new Error('联系电话重复'));
            }else{
              callback();
            }
          }).catch();
        }
      };
      var checkedCard = (rule, value, callback) => {
        if(this.updateEmpCard == value){
          callback();
        }else{
          this.$axios.get("http://localhost:8088/emp/emp_card",
            {params:{
                card:value
              }}).then(v=>{
            if(v.data == 1){
              callback(new Error('身份证号重复'));
            }else{
              callback();
            }
          }).catch();
        }

      };
      return {
        pageNum:1,
        pageSize:3,
        updateEmpname:'',
        updateEmpphone:'',
        updateEmpCard:'',
        empName:'',
        addUser:false,//新增用户
        tabPosition: 'left',//标签条方向在左边
        labelPosition: 'right',//表单右对齐
        title:'',//表单标题
        employeeDetails:{//用户详细
          empName:'',//用户名称
          empPhone:'',//联系电话
          empCard:'',//身份证号
          empSex:'',//性别
          empIsNot:'',//用户状态
          empAddress:'',//地址
          dateEntry:'',//入职日期
          deptName:'',//部门
          positionList:[]//职位
        },
        employee:{
          employeesId:0,//用户id
          empName:'',//用户名称
          empPhone:'',//联系电话
          empCard:'',//身份证号
          empSex:'',//性别
          empIsNot:'1',//用户状态
          empAddressProvince:'',//省
          empAddressCity:'',//市
          empAddressArea:'',//区
          empAddressDetailed:'',//详细地址
          dateEntry:'',//入职日期
          positionList:[],//已选的职位
          deptByDeptsId: {//部门
            deptsId:0,
            deptName:''
          },

        },
        employeeRules:{//表单验证
          empName:[
            {required: true, message: '用户名称不能为空!', trigger: 'blur' },
            { validator:checkedEmpName,trigger: 'blur' }
          ],
          empPhone:[
            {required: true, message: '联系电话不能为空!', trigger: 'blur' },
            {pattern: /^1[3456789]\d{9}$/,message: '联系电话号码格式错误！'},
            { validator:checkedPhone,trigger: 'blur' }
          ],
          empCard:[
            {required: true,message: '身份证号不能为空！',trigger: 'blur'},
            {pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证格式不正确!' },
            { validator:checkedCard,trigger: 'blur' }
          ],
          empSex:[
            {required: true,message: '性别不能为空！',trigger: 'blur'}
            ],
          'deptByDeptsId.deptName':[
            {required: true,message: '部门不能为空！',trigger: 'change'}
          ],
          positionList:[
              { type: 'array', required: true, message: "职位不能为空!", trigger: 'change' },
            ],
          empAddressArea:[
            {required: true,message: '地址不能为空！',trigger: 'change'}
          ],
          empAddressDetailed:[
            {required: true,message: '详细地址不能为空！',trigger: 'change'}
          ],
          dateEntry:[
            {required: true, message: '入职日期不能为空!', trigger: 'change' },
            ]
        },

        deptList:[],//所有部门
        positionList:[],//所有职位
        //查看个人详细信息
        userVisable:false,
        userInfo:[],//所有员工信息
        positionData:[],//临时存职位id
        perssionButton:[],
        postOne:0,
        id:'',
      }
    },
    created :function(){
      this.id = JSON.parse(sessionStorage.getItem("user")).employeesId;
      this.depts();//加载部门
      this.selectEmp(this.empName);
      this.initButton();
    },
    methods: {
      /*默认今天*/
      getNowTime() {
        var now = new Date();
        var year = now.getFullYear(); //得到年份
        var month = now.getMonth(); //得到月份
        var date = now.getDate(); //得到日期
        month = month + 1;
        month = month.toString().padStart(2, "0");
        date = date.toString().padStart(2, "0");
        var defaultDate = `${year}-${month}-${date}`;
       return defaultDate;
      },
      initButton(){
        this.perssionButton=JSON.parse(sessionStorage.getItem("button"));
      },
      //卡片分页
      handleClick(){
        this.pageNum = 1;
        this.pageSize = 3;
      },
      //前端分页
      handleSizeChange: function (size) {
        this.pageSize = size;
        console.log(this.pageSize)  //每页下拉显示数据
      },
      handleCurrentChange: function(currentPage){
        this.pageNum = currentPage;
        console.log(this.pageNum)  //点击第几页
      },
      //查询出部门
      depts(){
        this.$axios.get("http://localhost:8088/emp/depts").then(v=>{
          this.deptList = v.data;
        }).catch();
      },
      //查询出改部门下的角色
      findPosition(deptId){
        this.$axios.get("http://localhost:8088/emp/positions",
          {params:{deptId:deptId}}).then(v=>{
         this.positionList = v.data;
         this.$axios.get("http://localhost:8088/emp/is_first_post",
           {params:{
                deptId:deptId
           }}).then(v=>{
             if(v.data.number !=0 ){
               this.postOne = v.data.postId;
             }
         })
        }).catch();
      },

      //查询员工信息
      selectEmp(empName){
        this.$axios.get("http://localhost:8088/emp/select_emp",
          {params:{empName:empName}}).then(v=>{
         this.userInfo=v.data;
        }).catch();
      },
      ChangeProvince(v){
        this.employee.empAddressProvince=v.value;
      },
      ChangeCity(v){
        this.employee.empAddressCity=v.value;
      },
      ChangeArea(v){
        this.employee.empAddressArea=v.value;
      },
      //模糊查询用户名称
      searchEmp(val){
        this.pageNum = 1;
        this.pageSize = 3;
        this.selectEmp(val);
      },
      restPwd(emp){
        this.$confirm('此操作将初始化该用户的登录密码, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.post("http://localhost:8088/user/restPwd",
            this.qs.stringify({
                employeesId: emp.employeesId
              })).then(() => {
                if(emp.employeesId == JSON.parse(sessionStorage.getItem("user")).employeesId){
                  this.$router.push('/login');
                }else{
                  this.$message.success("重置成功");
                }
          }).catch();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消重置'
          });
        });
      },
      deleteEmp(emp){
        if(emp.employeesId == JSON.parse(sessionStorage.getItem("user")).employeesId){
          this.$message({
            type: 'error',
            message: '当前登录用户不可删除!'
          });
        }else{
          this.$confirm('此操作将删除用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if(emp.empIsNot == "1"){
              this.$message.error("启用用户不可删除!")
            }else{
              this.$axios.post("http://localhost:8088/emp/delete_emp",
                this.qs.stringify({empId:emp.employeesId})).then(()=>{
                this.$message.success("删除成功!");
                this. selectEmp(this.empName);//刷新用户数据
              }).catch();
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        }
      },
      //新增按钮
      addEmp(){
        if( this.$refs.employeeForm != undefined){
          this.$refs.employeeForm.resetFields();
        }
        this.title='新增用户';
        this.clearFrom();
        // getNowTime()
        this.employee.dateEntry = this.getNowTime();
        console.log("当前时间:"+this.getNowTime());
        this.addUser=true;
      },

      updateEmp(dept,emp){
        this.updateEmpname=emp.empName;
        this.updateEmpphone = emp.empPhone;
        this.updateEmpCard  = emp.empCard;
        if( this.$refs.employeeForm != undefined){
          this.$refs.employeeForm.resetFields();
        }
        this.employee.positionList=[];//清空
        this.title='修改用户';
        this.employee.employeesId=emp.employeesId;
        this.employee.empName=emp.empName;//用户名称
        this.employee.empPhone=emp.empPhone;//联系电话
        this.employee.empSex=emp.empSex;//性别
        this.employee.empCard=emp.empCard;//身份证号
        this.employee.dateEntry=emp.dateEntry;//入职日期
        this.employee.empIsNot=emp.empIsNot;//用户状态
        this.employee.empAddressProvince=emp.empAddressProvince;//省
        this.employee.empAddressCity=emp.empAddressCity;//市
        this.employee.empAddressArea=emp.empAddressArea;//区
        this.employee.empAddressDetailed=emp.empAddressDetailed;//详细地址
        this.employee.deptByDeptsId.deptsId = dept.deptsId;
        this.employee.deptByDeptsId.deptName = dept.deptName;
        console.log("Lll:"+this.employee.deptByDeptsId.deptName);
        emp.positionVos.forEach(item=>{
          this.employee.positionList.push(item.value);
        })
        this.depts();
        this.findPosition( this.employee.deptByDeptsId.deptsId);
        this.addUser=true;
      },
      //新增或修改员工
      saveEmp(){
        this.$refs.employeeForm.validate((valid) => {
          if (valid) {
           //处理角色数据
            this.positionList = this.employee.positionList;//把id存到临时数组
            this.employee.positionList = [];//清空
            this.positionList.forEach(item=>{
              this.employee.positionList.push({"postId":item});
            })

            this.$axios.post("http://localhost:8088/emp/save_emp",this.employee).then(()=>{
              this.$refs.employeeForm.resetFields();
              if(this.employee.employeesId==0){
                this.$message.success("新增成功!");
              }else{
                this.$message.success("修改成功!")
              }
              this.positionList = [];
              this.clearFrom();//清空
              this. selectEmp(this.empName);
              this.addUser=false;
            }).catch();
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
        //清空表单
      clearFrom(){
        this.employee={
          employeesId:0,//用户id
            empName:'',//用户名称
            empPhone:'',//联系电话
            empCard:'',//身份证号
            empSex:'',//性别
            empIsNot:'1',//用户状态
            empAddressProvince:'',//省
            empAddressCity:'',//市
            empAddressArea:'',//区
            empAddressDetailed:'',//详细地址
            dateEntry:'',//入职日期
            deptByDeptsId: {//部门
              deptsId:0,
              deptName:''
            },
          positionList:[]

        }
      },
      //改变员工的状态
      updateEmpStatus(val){

          this.$axios.post("http://localhost:8088/emp/update_emp_status",
            this.qs.stringify({employeesId:val.employeesId,empIsNot:val.empIsNot})).then(()=>{
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          }).catch();
      },

      //查看详细信息
      userdetails(dept,emp){
        this.employeeDetails.deptName=dept.deptName;//部门
        this.employeeDetails.empName=emp.empName;//用户名称
        this.employeeDetails.empPhone=emp.empPhone;//联系电话
        this.employeeDetails.empSex=emp.empSex;//性别
        this.employeeDetails.empCard=emp.empCard;//身份证号
        this.employeeDetails.dateEntry=emp.dateEntry;//入职日期
        this.employeeDetails.postName=emp.postName;//职务
        this.employeeDetails.empIsNot=emp.empIsNot>'0'?'启用':'禁用';
        this.employeeDetails.empAddress=emp.empAddressProvince+emp.empAddressCity+emp.empAddressArea+emp.empAddressDetailed;
        this.employeeDetails.positionList = emp.positionVos;
        this.userVisable=true;
      },
    }
  }

</script>

<style>
  .container {
    padding: 20px;
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 5px;
    box-shadow:#ccc 0px 0px 10px;
  }


  .mgb20 {
    margin-bottom: 20px;
  }
  .user-info {
    display: flex;
    align-items: center;
    padding-bottom: 20px;
    border-bottom: 2px solid #ccc;
    margin-bottom: 20px;
    cursor:pointer;
  }

  .user-info-cont {
    padding-left: 50px;
    flex: 1;
    font-size: 14px;
    color: #999;
  }
  .user-info-cont div:first-child {
    font-size: 20px;
    color: #222;
    margin-bottom: 10px;
  }
  .user-info-list {
    font-size: 14px;
    color: #999;
    line-height: 25px;
  }
  .dialog_sty{
    border:1px solid #409eff;
    width: 95%;
    margin: 10px auto;
  }
  .perm_sty{
    width: 100%;
  }
  .el-dialog__body{
   padding: 0px 20px;
  }
  .jiaImg{
    margin-top: -34px;
    cursor: pointer;
    position: relative;
    left: 13%;
  }
  .distpicker-address-wrapper select {
    width: 80px;
  }

  .userInfomantion  .el-input__inner{
    border-top:none;
    border-left: none;
    border-right: none;
    border-radius:0px;
  }
</style>

